package cn.qyd.aqs;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 邱运铎
 * @date 2024-03-20 12:23
 */
public class ConditionPrintABC {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();
    private final Condition conditionD = lock.newCondition();
    public void printA() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "print ---- A");
            conditionD.await();
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "print ---- B");
            conditionA.await();
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "print ---- C");
            conditionB.await();
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printD() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "print ---- D");
            conditionD.signal();
            conditionC.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionPrintABC demo = new ConditionPrintABC();
        Thread tA = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printA();
            }
        });
        Thread tB = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printB();
            }
        });
        Thread tC = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printC();
            }
        });

        Thread tD = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printD();
            }
        });

        tA.start();
        Thread.sleep(100);
        tB.start();
        Thread.sleep(100);
        tC.start();
        Thread.sleep(100);
        tD.start();
    }
}
